package com.ganlucode.sipmock.sip;

import com.ganlucode.sipmock.sip.mock.ISipMock;
import com.ganlucode.sipmock.sip.mock.entity.MockParam;
import com.ganlucode.sipmock.sip.mock.entity.RegisterParam;
import com.ganlucode.sipmock.sip.request.ISipRequestProcessor;
import com.ganlucode.sipmock.sip.response.ISipResponseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sip.*;
import javax.sip.header.WWWAuthenticateHeader;
import javax.sip.message.Response;

/**
 * @author GanLu
 * @date 2020-05-14 20:40
 */
@Slf4j
@Component("sipListener")
public class SipListenerImpl implements SipListener {


    @Autowired
    @Qualifier("requestProcessorProxy")
    private ISipRequestProcessor requestProcessorProxy;
    @Autowired
    @Qualifier("responseProcessorProxy")
    private ISipResponseProcessor responseProcessorProxy;

    @Autowired
    @Qualifier("registerMock")
    private ISipMock registerMock;

    /**
     * SIP服务端接收消息的方法 Content 里面是GBK编码 This method is called by the SIP stack when a
     * new request arrives.
     */
    @Override
    public void processRequest(RequestEvent requestEvent) {
        try {
            requestProcessorProxy.process(requestEvent);
        } catch (Exception e) {
            log.error("处理消息请求异常", e);
        }
    }

    @Override
    public void processResponse(ResponseEvent responseEvent) {
        Response response = responseEvent.getResponse();
        int status = response.getStatusCode();
        if ((status >= 200) && (status < 300)) {
            // Success!
            try {
                responseProcessorProxy.process(responseEvent);
            } catch (Exception e) {
                log.error("处理消息响应异常", e);
            }
        }else if (status == Response.UNAUTHORIZED){
            //401携带认证重新注册
            WWWAuthenticateHeader authenticateHeader =
                    (WWWAuthenticateHeader) response.getHeader(WWWAuthenticateHeader.NAME);
            RegisterParam registerParam = new RegisterParam(true, authenticateHeader);
            try {
                registerMock.start(new MockParam(registerParam));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (status == Response.TRYING) {
            // trying不会回复
            log.info("Trying消息");
        } else {
            log.warn("接收到失败的response响应！status:{},message:{}", status, response.getContent());
        }

    }

    @Override
    public void processTimeout(TimeoutEvent timeoutEvent) {
        log.info("Timeout");
    }

    @Override
    public void processIOException(IOExceptionEvent exceptionEvent) {
        log.info("IOException");
    }

    @Override
    public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
        log.info("TransactionTerminated");
    }

    @Override
    public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
        log.info("DialogTerminated");
    }
}
